package com.zelin.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.zelin.common.to.es.SkuEsModel;
import com.zelin.gulimall.search.config.GulimallElasticSearchConfig;
import com.zelin.gulimall.search.constant.EsConstant;
import com.zelin.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by WF on 2021/1/8 17:28
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    private RestHighLevelClient client;
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId() + "");    //文档id
            //将数据转换为字符串
            String string = JSON.toJSONString(skuEsModel);
            indexRequest.source(string, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = client.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

        boolean b = bulk.hasFailures();     //true:代表失败
        List<Integer> ids = Arrays.stream(bulk.getItems())
                                  .map(m ->m.getItemId())
                                  .collect(Collectors.toList());
        log.info("商品上架完成：{}，返回数据：{}",ids,bulk.toString());
        return b;
    }
}
